import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from '../components/Index.vue'
import Register from '../components/Register.vue'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import UserSet from '../components/user/Set.vue'
import Avator from '../components//user/Avator.vue'
import Bio from '../components//user/Bio.vue'
import Point from '../components//user/Point.vue'
import Section from '../components/publish/Section.vue'
import Publish from '../components/publish/Publish.vue'
import User from '../components/user/User.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/index'
  },
  {
    path: '/register',
    component: Register
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/index',
    component: Index,
    redirect: {
      name: 'home'
    },
    children: [
      {
        path: '/home',
        name: 'home',
        component: Home
      },
      {
        path: '/index/set',
        component: UserSet,
        redirect: '/index/set/avator',
        children: [
          {
            path: '/index/set/avator',
            component: Avator
          },
          {
            path: '/index/set/Bio',
            component: Bio
          },
          {
            path: '/index/set/point',
            component: Point
          }
        ]
      },
      {
        path: '/home/publish',
        component: Publish
      },
      {
        path: '/home/section/:id',
        name: 'section',
        component: Section,
        props: true
      },
      {
        path: '/home/user/:name',
        name: 'user',
        component: User,
        props: true
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // if (to.path === '/login') return next()
  // const tokenStr = JSON.parse(window.sessionStorage.getItem('token'))
  // if (!tokenStr) return next('/login')
  // next()
  if (to.matched.some(record => record.meta.requireLogin)) {
    const tokenStr = JSON.parse(window.sessionStorage.getItem('token'))
    if (!tokenStr) return next('/login')
  } else {
    next()
  }
})

export default router
